<template>
  <div
    class="user-wrapper"
    :class="theme"
    :style="{ display: isDesktop() ? 'flex' : 'block', 'align-items': 'center' }"
  >
    <!-- update_begin author:zhaoxin date:20191129 for: 做头部菜单栏导航 -->
    <!-- update-begin author:sunjianlei date:20191@20 for: 解决全局样式冲突的问题 -->
    <span class="action" v-if="tenantid">
      <a-badge :count="count" :offset="[count > 9 ? [5, 0] : [0, 0]]" @click="viewWarn">
        <a-icon type="bell" style="font-size: 16px; padding: 4px" />
      </a-badge>
    </span>
    <a-dropdown @visibleChange="getCollention" placement="bottomRight" :trigger="['click']">
      <span class="action user-dropdown-menu">
        <a-icon type="star" />
        <span style="padding-left: 4px" v-if="!isMobile()">{{ $t('收藏') }}</span>
      </span>
      <a-menu slot="overlay" class="user-dropdown-menu-wrapper">
        <a-menu-item :key="menu.permissionId" v-for="menu in collections" @click="toLink(menu)" @mouseenter="handleMouseEnter" @mouseleave="handleMouseLeave">
          <div style="display: flex; justify-content: space-between; align-items: center">
            <span>{{ menu.permissionName }}</span>
            <a-icon
              class="star-icon0"
              type="star"
              theme="filled"
              :style="{
                color: 'orange',
                cursor: 'pointer',
                opacity: 0,
                transition: 'opacity 0.3s',
              }"
              @click="(event) => handleFavClick(event, menu)"
            />
          </div>
        </a-menu-item>
      </a-menu>
    </a-dropdown>
    <span class="action" @click="viewHelp">
      <a-icon type="question-circle" />
      <span style="padding-left: 4px" v-if="!isMobile()">{{ $t('帮助') }}</span>
    </span>
    <a-dropdown placement="bottomRight" :trigger="['click']">
      <span class="action user-dropdown-menu" @click="e => e.preventDefault()">
        <img src="../../assets/langicon.png" style="width:24px;height:24px" /><a-icon type="down" />
      </span>
      <a-menu slot="overlay">
        <a-menu-item v-for="(item) in langs" :key="item.code" @click="changeLang(item.code)">
          <a href="javascript:;">{{ item.name }}</a>
        </a-menu-item>
      </a-menu>
    </a-dropdown>
    <span class="action" @click="showClick">
      <a-icon type="search"></a-icon>
      <span style="padding-left: 4px" v-if="!isMobile()">{{ $t('搜索菜单') }}</span>
    </span>
    <!-- update-begin author:sunjianlei date:20200219 for: 菜单搜索改为动态组件，在手机端呈现出弹出框 -->
    <component
      :is="searchMenuComp"
      v-show="isMobile()"
      class="borders"
      :visible="searchMenuVisible"
      :title="$t('搜索菜单')"
      :footer="null"
      @cancel="searchMenuVisible = false"
    >
      <a-select
        class="search-input"
        showSearch
        allowClear
        :showArrow="false"
        :placeholder="$t('搜索菜单')"
        optionFilterProp="children"
        :filterOption="filterOption"
        :open="isMobile() ? true : null"
        :getPopupContainer="(node) => node.parentNode"
        :style="isMobile() ? { width: '100%', marginBottom: '50px' } : { marginLeft: '6px' }"
        @change="searchMethods"
        @blur="hiddenClick"
      >
        <a-select-option v-for="(site, index) in searchMenuOptions" :key="index" :value="site.id">{{
          site.meta.title
        }}</a-select-option>
      </a-select>
    </component>
    <!-- update-end author:sunjianlei date:20200219 for: 菜单搜索改为动态组件，在手机端呈现出弹出框 -->
    <!-- update-end author:sunjianlei date:20191220 for: 解决全局样式冲突的问题 -->
    <!-- update_end  author:zhaoxin date:20191129 for: 做头部菜单栏导航 -->
    <!-- <span class="action">
      <a class="logout_title" target="_self" href="/isystem/6e6f726c8023bf1db60d6b14b8775f1f">
        <a-icon type="question-circle-o"></a-icon>
      </a>
    </span> -->
    <a-dropdown>
      <span class="action user-dropdown-menu">
        <a-avatar size="small" :src="getAvatar()" icon="user" />
        <span v-if="isDesktop()" style="padding-left: 4px">{{ $t('欢迎您，') }}{{ nickname() }}</span>
      </span>
      <a-menu slot="overlay" class="user-dropdown-menu-wrapper">
        <a-menu-item key="4" @click="updatePassword">
          <a-icon type="setting" />
          <span>{{ $t('密码修改') }}</span>
        </a-menu-item>
        <a-menu-item key="6" @click="clearCache">
          <a-icon type="sync" />
          <span>{{ $t('清理缓存') }}</span>
        </a-menu-item>
        <a-menu-item key="2" @click="aboutSystem">
          <a-icon type="setting" />
          <span>{{ $t('系统关于') }}</span>
        </a-menu-item>
      </a-menu>
    </a-dropdown>
    <span class="action">
      <a class="logout_title" href="javascript:;" @click="handleLogout">
        <a-icon type="logout" />
        <span v-if="isDesktop()">&nbsp;{{ $t('退出登录') }}</span>
      </a>
    </span>
    <user-password ref="userPassword"></user-password>
    <depart-select ref="departSelect" :closable="true" :title="$t('部门切换')"></depart-select>
    <setting-drawer ref="settingDrawer" :closable="true" :title="$t('系统设置')"></setting-drawer>
    <about-system ref="aboutSystem" :closable="true" :title="$t('关于系统')"></about-system>
    <warn-modal ref="warnModal"></warn-modal>
    <user-remind-modal ref="remindModal" @ok="updatePassword"></user-remind-modal>
    <authorize-modal ref="modalForm"></authorize-modal>
    <search-menu-modal ref="searchMenu" @cancleFav="cancleFav" />
  </div>
</template>

<script>
import HeaderNotice from './HeaderNotice'
import UserPassword from './UserPassword'
import AboutSystem from './AboutSystem'
import SettingDrawer from '@/components/setting/SettingDrawer'
import DepartSelect from './DepartSelect'
import { mapActions, mapGetters, mapState } from 'vuex'
import { mixinDevice } from '@/utils/mixin.js'
import { getFileAccessHttpUrl, getAction, postAction, deleteAction } from '@/api/manage'
import {TENANT_ID, UI_CACHE_DB_DICT_DATA} from '@/store/mutation-types'
import Vue from 'vue'
import WarnModal from './WarnModal'
import UserRemindModal from './UserRemindModal'
import AuthorizeModal from './AuthorizeModal'
import SearchMenuModal from './SearchMenuModal'
import store from '@/store/'

export default {
  name: 'UserMenu',
  mixins: [mixinDevice],
  data() {
    return {
      // update-begin author:sunjianlei date:20200219 for: 头部菜单搜索规范命名 --------------
      searchMenuOptions: [],
      searchMenuComp: 'span',
      searchMenuVisible: true,
      count: 0,
      // update-begin author:sunjianlei date:20200219 for: 头部菜单搜索规范命名 --------------
      tenantid: Vue.ls.get('TENANT_ID'),
      websock: null,
      lockReconnect: false,
      lang: localStorage.getItem('language'),
      langs: [],
      collections: [],
    }
  },
  components: {
    HeaderNotice,
    UserPassword,
    DepartSelect,
    SettingDrawer,
    AboutSystem,
    WarnModal,
    UserRemindModal,
    AuthorizeModal,
    SearchMenuModal
  },
  props: {
    theme: {
      type: String,
      required: false,
      default: 'dark',
    },
  },
  /* update_begin author:zhaoxin date:20191129 for: 做头部菜单栏导航*/
  async created() {
    await this.getAllDictItems()
    await this.getLanguage()
    await this.getSet()
    let lists = []
    this.searchMenus(lists, this.permissionMenuList)
    this.searchMenuOptions = [...lists]
  },
  mounted() {
    //如果是单点登录模式F
    if (process.env.VUE_APP_SSO == 'true') {
      let depart = this.userInfo().orgCode
      if (!depart) {
        this.updateCurrentDepart()
      }
    }
    getAction('/report/home/systemWarning').then((res) => {
      if (res.success) {
        this.count = 0
        if (res.result.giftBalance !== undefined) {
          this.count = 1
        }
        if (res.result.systemValid !== undefined) {
          this.count += 1
        }
        this.count =
          this.count +
          res.result.allotOrder +
          res.result.backOrder +
          res.result.buyOrder +
          res.result.lossOrder +
          res.result.inOrder + 
          (res.result.barNotice?res.result.barNotice.length:0)
      } else {
        this.$message.error(res.message)
      }
    })
    this.lockReconnect = false
    this.initWebSocket()
    this.userRemind()
  },
  computed: {
    ...mapState({
      // 后台菜单
      permissionMenuList: (state) => state.user.permissionList,
    }),
  },
  /* update_end author:zhaoxin date:20191129 for: 做头部菜单栏导航*/
  watch: {
    // update-begin author:sunjianlei date:20200219 for: 菜单搜索改为动态组件，在手机端呈现出弹出框
    device: {
      immediate: true,
      handler() {
        this.searchMenuVisible = this.isMobile() ? false : true
        this.searchMenuComp = this.isMobile() ? 'a-modal' : 'span'
      },
    },
    // update-end author:sunjianlei date:20200219 for: 菜单搜索改为动态组件，在手机端呈现出弹出框
  },
  methods: {
    handleMouseEnter(event) {
      event.domEvent.target.querySelector('.star-icon0').style.opacity = 1
    },
    handleMouseLeave(event) {
      event.domEvent.target.querySelector('.star-icon0').style.opacity = 0
    },
    toLink(menu) {
      this.$router.push({
        path: menu.url,
      })
    },
    handleFavClick(event, menu) {
      event.stopPropagation() // 阻止事件冒泡
      event.preventDefault() // 阻止默认行为（如果有）
      // 切换收藏状态，使用 Vue.set 确保响应式
      // 这里可以添加你的收藏逻辑，比如发送请求到后端保存收藏状态
      deleteAction('/sys/myCollection/delete', {
        id: menu.permissionId,
      }).then((res) => {
        if (res.success) {
          this.getCollention(true)
          this.$forceUpdate()
          this.$emit('cancleFav', menu.permissionId)
        }
      })
    },
    cancleFav(permissionId){
      this.$emit('cancleFav', permissionId)
    },
    getCollention(visible) {
      if (visible) {
        getAction('/sys/myCollection/list', { userId: this.userInfo().id }).then((res) => {
          if (res.success) {
            this.collections = res.result
          } else {
            this.collections = []
          }
        })
      }
    },
    viewHelp() {
      this.$refs.modalForm.show()
    },
    getLanguage() {
      return new Promise((resolve) => {
        getAction('/guest/system/getLanguage').then((res) => {
          if (res.success) {
            this.langs = res.result
          }
          resolve()
        })
      })
    },
    getSet() {
      return new Promise((resolve) => {
        getAction('/bis/bisSysParameter/queryByName', {name : "userSecurityPwd"}).then((res) => {
          if (res.success && res.result && res.result.ivalue == 0) {
            localStorage.setItem('freePass', true)
          } else {
            localStorage.setItem('freePass', false)
          }
          resolve()
        })
      })
    },
    async changeLang(e) {
      plugin.setLan(e, 'language')
      await this.getAllDictItems()
      let tid=Vue.ls.get(TENANT_ID);
      if (tid)
      {
        if (window.location.href.indexOf("?")>0) {
          window.location.href = window.location.href + "&id=" + tid;
        }
        else {
          window.location.href = window.location.href + "?id=" + tid;
        }
      }
      else {
        window.location.reload()
      }
    },
    userRemind() {
      getAction('system/user/remind', {}).then((res) => {
        if (res.success && res.result !== undefined && res.result !== null) {
          this.$refs.remindModal.show(res.result)
        }
      })
    },
    // update-end-author:sunjianlei date:20210508 for: 修复动态功能测试菜单、带参数菜单标题错误、展开错误的问题
    initWebSocket: function () {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var userId = store.getters.userInfo.id
      var url =
        window._CONFIG['domianURL'].replace('https://', 'wss://').replace('http://', 'ws://') +
        'websocket/' +
        userId +
        '_' +
        localStorage.getItem('randomStr')
      this.websock = new WebSocket(url)
      this.websock.onopen = this.websocketOnopen
      this.websock.onerror = this.websocketOnerror
      this.websock.onmessage = this.websocketOnmessage
      this.websock.onclose = this.websocketOnclose
    },
    websocketOnopen: function () {
      console.log('WebSocket连接成功')
    },
    websocketOnerror: function (e) {
      console.log('WebSocket连接发生错误')
      this.reconnect()
    },
    websocketOnmessage: function (e) {
      let that = this
      var data = eval('(' + e.data + ')') //解析对象
      console.log('-----接收消息-------', e.data)
      if (data.cmd == 'user') {
        //用户消息
        that.$warning({
          title: that.$t('提示'),
          content: that.$t('您的账号已在别处登录，请确保是否本人操作，为了安全起见您可进行密码变更。'),
          keyboard: false,
          okText: that.$t('确定'),
          onOk() {
            that.lockReconnect = true
            that.websock.close()
            that
              .Logout({})
              .then(() => {
                let tid=Vue.ls.get(TENANT_ID);
                if (tid)
                {
                  if (window.location.href.indexOf("?")>0) {
                    window.location.href = window.location.href + "&id=" + tid;
                  }
                  else {
                    window.location.href = window.location.href + "?id=" + tid;
                  }
                }
                else {
                  window.location.reload()
                }
              })
              .catch((err) => {
                that.$message.error({
                  title: that.$t('错误'),
                  description: err.message,
                })
              })
          },
        })
      }
    },
    websocketOnclose: function (e) {
      console.log('connection closed (' + e + ')')
      if (e) {
        console.log('connection closed (' + e.code + ')')
      }
      this.reconnect()
    },
    websocketSend(text) {
      // 数据发送
      try {
        this.websock.send(text)
      } catch (err) {
        console.log('send failed (' + err.code + ')')
      }
    },
    reconnect() {
      var that = this
      if (that.lockReconnect) return
      that.lockReconnect = true
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info('尝试重连...')
        that.initWebSocket()
        that.lockReconnect = false
      }, 5000)
    },
    /* update_begin author:zhaoxin date:20191129 for: 做头部菜单栏导航*/
    showClick() {      
      if(this.isMobile()){
        this.searchMenuVisible = true
      }else{
        this.$refs.searchMenu.show(this.searchMenuOptions)
      }
    },
    hiddenClick() {
      this.shows = false
    },
    /* update_end author:zhaoxin date:20191129 for: 做头部菜单栏导航*/
    ...mapActions(['Logout']),
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    getAvatar() {
      return getFileAccessHttpUrl(this.avatar())
    },
    handleLogout() {
      let that = this
      that.$confirm({
        title: that.$t('提示'),
        content: that.$t('真的要注销登录吗 ?'),
        okText: this.$t('确定'),
        cancelText: this.$t('取消'),
        onOk() {
          return that
            .Logout({})
            .then(() => {
              // update-begin author:scott date:20211223 for:【JTC-198】退出登录体验不好
              //that.$router.push({ path: '/user/login' });
              let tid=Vue.ls.get(TENANT_ID);
              if (tid)
              {
                if (window.location.href.indexOf("?")>0) {
                  window.location.href = window.location.href + "&id=" + tid;
                }
                else {
                  window.location.href = window.location.href + "?id=" + tid;
                }
              }
              else {
                window.location.reload()
              }
              // update-end author:scott date:20211223 for:【JTC-198】退出登录体验不好
            })
            .catch((err) => {
              that.$message.error({
                title: that.$t('错误'),
                description: err.message,
              })
            })
        },
        onCancel() {},
      })
    },
    updatePassword() {
      let username = this.userInfo().username
      this.$refs.userPassword.show(username)
    },
    aboutSystem() {
      this.$refs.aboutSystem.show()
    },
    updateCurrentDepart() {
      this.$refs.departSelect.show()
    },
    viewWarn() {
      this.$refs.warnModal.show()
    },
    systemSetting() {
      this.$refs.settingDrawer.showDrawer()
    },
    /* update_begin author:zhaoxin date:20191129 for: 做头部菜单栏导航*/
    searchMenus(arr, menus) {
      for (let i of menus) {
        if (!i.hidden && 'layouts/RouteView' !== i.component) {
          arr.push(i)
        }
        if (i.children && i.children.length > 0) {
          this.searchMenus(arr, i.children)
        }
      }
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    // update_begin author:sunjianlei date:20191230 for: 解决外部链接打开失败的问题
    searchMethods(value) {
      let route = this.searchMenuOptions.filter((item) => item.id === value)[0]
      //update-begin-author:sunjianlei date:20220111 for: 【JTC-702】【菜单搜索】菜单搜索里点击跳转的菜单，无法将Token信息传递过去
      if (route.component.includes('layouts/IframePageView')) {
        this.$router.push(route)
      } else {
        this.$router.push({ path: route.path })
      }
      //update-end-author:sunjianlei date:20220111 for: 【JTC-702】【菜单搜索】菜单搜索里点击跳转的菜单，无法将Token信息传递过去
      this.searchMenuVisible = this.isMobile() ? false : true
    },
    // update_end author:sunjianlei date:20191230 for: 解决外部链接打开失败的问题
    /*update_end author:zhaoxin date:20191129 for: 做头部菜单栏导航*/
    /*update_begin author:liushaoqian date:20200507 for: 刷新缓存*/
    clearCache() {
      getAction('sys/dict/refleshCache')
        .then((res) => {
          if (res.success) {
            //重新加载缓存
            this.getAllDictItems()
            /* getAction('sys/dict/queryAllDictItems').then((res) => {
              if (res.success) {
                Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
                Vue.ls.set(UI_CACHE_DB_DICT_DATA, res.result, 7 * 24 * 60 * 60 * 1000)
              }
            }) */
            this.$message.success(this.$t('刷新缓存完成'))
          }
        })
        .catch((e) => {
          this.$message.warn(this.$t('刷新缓存失败'))
          console.log('刷新失败', e)
        })
    },
    /*update_end author:liushaoqian date:20200507 for: 刷新缓存*/
    getAllDictItems() {
      return new Promise((resolve) => {
        getAction('sys/dict/queryAllDictItems').then((res) => {
          if (res.success) {
            Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
            Vue.ls.set(UI_CACHE_DB_DICT_DATA, res.result, 7 * 24 * 60 * 60 * 1000)
          }
          resolve()
        })
      })
    },
  },
}
</script>

<style lang="less" scoped>
/* update_begin author:zhaoxin date:20191129 for: 让搜索框颜色能随主题颜色变换*/
/* update-begin author:sunjianlei date:20191220 for: 解决全局样式冲突问题 */
.user-wrapper .search-input {
  width: 180px;
  color: inherit;

  /deep/ .ant-select-selection {
    background-color: inherit;
    //border: 0;
    //border-bottom: 1px solid white;
    &__placeholder,
    &__field__placeholder {
      color: inherit;
    }
  }
}
/* update-end author:sunjianlei date:20191220 for: 解决全局样式冲突问题 */
/* update_end author:zhaoxin date:20191129 for: 让搜索框颜色能随主题颜色变换*/
</style>

<style scoped>
.logout_title {
  color: inherit;
  text-decoration: none;
}
</style>